<template>
    <div>
        <el-form :model="params">
            <el-row :gutter="24">
                <el-col :span="7">
                    <el-form-item label="入库单编号">
                        <el-input placeholder="请输入编号" v-model="params.recptCode" clearable
                            :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="7">
                    <el-form-item label="入库单名称">
                        <el-input placeholder="请输入名称" v-model="params.recptName" clearable
                            :style="{ width: '100%' }"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="7">
                    <el-form-item label="入库日期">
                        <el-date-picker v-model="params.recptDate" align="right" type="date" placeholder="选择日期"
                            :picker-options="pickerOptions">
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
                <el-button type="primary" plain @click="paramsReset" :icon="Refresh">重置</el-button>
            </el-row>
        </el-form>


        <el-button style="background-color:#ADD8E6" @click="insert" :icon="Plus">新增</el-button>
        <el-button style=" background-color: #90EE90" :icon="Edit" @click="updateid"
            :disabled="isSingleRowSelected">修改</el-button>
        <el-button style="background-color: #FFCCCB" @click="DeleteRKD" plain :disabled="deleteDisabled"
            :icon="Delete">删除</el-button>

        <div style="display: flex; flex-direction: column; gap: 10px;">
            <el-table style="width: 100%" :data="salesorder" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="50"></el-table-column>
                <el-table-column prop="recptCode" label="入库单编码" width="150"></el-table-column>
                <el-table-column prop="recptName" label="入库单名称" width="150"></el-table-column>
                <el-table-column prop="workorderCode" label="生产工单编码" width="250"></el-table-column>
                <el-table-column prop="productCode" label="产品编码" width="250"></el-table-column>
                <el-table-column prop="productName" label="产品名称" width="150"></el-table-column>
                <el-table-column prop="recptDate" label="入库日期" width="150"></el-table-column>
                <el-table-column prop="status" label="单据状态" width="150">
                    <template #default="scope">
                        {{ scope.row.status === 'PREPARE' ? '草稿' : '已完成' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="300">
                    <template #default="scope">
                        <!-- 只有在状态为草稿时显示修改和删除按钮 -->
                        <div v-if="scope.row.status === 'PREPARE'">
                            <el-button link type="primary" @click="rk(scope.row)" :icon="Edit">执行入库</el-button>
                            <el-button link type="primary" @click="update(scope.row)" :icon="Edit">修改</el-button>
                            <el-button type="primary" link @click="DeleteRKD1(scope.row)" :icon="Delete">删除</el-button>
                        </div>
                        <!-- 当状态为已完成时，不显示任何按钮 -->
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-row>
            <el-col :span="24">
                <div class="demo-pagination-block">
                    <el-pagination :current-page="params.currentPage" :page-size="params.pageSize" background
                        :default-page-size="params.pageSize" :page-sizes="pageSizes"
                        layout="total,sizes,prev,pager,next,jumper" :total="pageResult.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-col>
        </el-row>


        <!-- 新增入库单弹窗 -->
        <el-dialog :destroy-on-close="true" :title="title" v-model="visible" width="60%" @close="handleClose">
            <el-form ref="form" :model="formdata" label-width="100px">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="入库单编号">
                            <el-input v-model="formdata.recptCode" placeholder="请输入编号"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="入库单名称">
                            <el-input v-model="formdata.recptName" placeholder="请输入名称"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="生产工单">
                            <el-input v-model="formdata.workorderCode" style="max-width: 600px" placeholder="请选择"
                                readonly>
                                <template #append>
                                    <el-button :icon="Search" @click="customerSelect" />
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="工单名称">
                            <el-input v-model="formdata.workorderName"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="入库日期">
                            <el-date-picker v-model="formdata.recptDate" type="date" placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="formdata.remark" placeholder="请输入备注"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmit">确定</el-button>
                    <el-button @click="close">关闭</el-button>
                </div>
            </template>


            <el-tabs type="border-card" v-show="activeName">
                <el-tab-pane label="物料信息">
                    <el-button style="background-color:#ADD8E6" @click="cpinsert">新增</el-button>
                    <el-button style="background-color: #FFCCCB" plain :disabled="deleteDisabled"
                        @click="deletecp">删除</el-button>
                    <el-table style="width: 100%" :data="formdata.line" @selection-change="handleSelectionChangebom">
                        <el-table-column type="selection" width="50"></el-table-column>
                        <el-table-column prop="productCode" label="产品编码" width="100"></el-table-column>
                        <el-table-column prop="productName" label="产品名称" width="100"></el-table-column>
                        <el-table-column prop="specificationAndModel" label="规格型号" width="100"></el-table-column>
                        <el-table-column prop="unitId" label="单位" width="100"></el-table-column>
                        <el-table-column prop="quantityRecived" label="入库数量" width="100"></el-table-column>
                        <el-table-column prop="batchCode" label="批次号" width="100"></el-table-column>
                        <el-table-column prop="warehouseName" label="仓库" width="100"></el-table-column>
                        <el-table-column prop="warehouseName" label="库区" width="100"></el-table-column>
                        <el-table-column prop="locationName" label="库位" width="100"></el-table-column>
                        <el-table-column prop="expireDate" label="有效期" width="200"></el-table-column>
                        <el-table-column prop="remark" label="备注" width="100"></el-table-column>
                        <el-table-column label="操作" width="200px">
                            <template #default="scope">
                                <el-button :row="scope.row" link type="primary" @click="cpupdate(scope.row)"
                                    :icon="Edit">修改</el-button>
                                <el-button type="primary" link @click="Deletecp1(scope.row)"
                                    :icon="Delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 分页组件 -->
                <el-row>
                    <el-col :span="24">
                        <div class="demo-pagination-block">
                            <el-pagination v-model:current-page="paramsline.currentPage"
                                v-model:page-size="paramsline.pageSize" background
                                :default-page-size="paramsline.pageSize" :page-sizes="pageSizesline"
                                layout="total,sizes,prev,pager,next,jumper" :total="parseInt(pageResultline.total)"
                                @size-change="handleSizeChangeline" @current-change="handleCurrentChangeline">
                            </el-pagination>
                        </div>
                    </el-col>
                </el-row>
                <!-- 分页组件结束 -->
            </el-tabs>
        </el-dialog>

        <!-- 查询工单弹窗 -->
        <el-dialog :destroy-on-close="true" :gdtitle="gdtitle" v-model="gdvisible" width="80%" @close="handleClose2">
            <el-form :inline="true" :model="proWorkorder">
                <el-form-item label="工单编码" :class="{ 'bold-label': true }">
                    <el-input v-model="proWorkorder.workorderCode" placeholder="请输入工单编码" clearable />
                </el-form-item>
                <el-form-item label="工单名称" :class="{ 'bold-label': true }">
                    <el-input v-model="proWorkorder.workorderName" placeholder="请输入工单名称" clearable />
                </el-form-item>

                <el-form-item label="产品编码" :class="{ 'bold-label': true }">
                    <el-input v-model="proWorkorder.productCode" placeholder="请输入产品编码" clearable />
                </el-form-item>
                <el-form-item label="产品名称" :class="{ 'bold-label': true }">
                    <el-input v-model="proWorkorder.productName" placeholder="请输入产品名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-button :icon="Search" type="primary" @click="onSearch">搜索</el-button>
                    <el-button :icon="Refresh" plain @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
            <div style="display: flex; flex-direction: column; gap: 10px;">
                <el-table style="width: 100%" :data="gdsalesorder" @row-click="handleRowClick">
                    <el-table-column prop="workorderCode" label="工单编码" width="200"></el-table-column>
                    <el-table-column prop="workorderName" label="工单名称" width="150"></el-table-column>
                    <el-table-column prop="orderSource" label="工单来源" width="150"></el-table-column>
                    <el-table-column prop="clientOrderCode" label="订单编号" width="150"></el-table-column>
                    <el-table-column prop="productCode" label="产品编码" width="150"></el-table-column>
                    <el-table-column prop="productName" label="产品名称" width="150"></el-table-column>
                    <el-table-column prop="productSpc" label="规格型号" width="150"></el-table-column>
                    <el-table-column prop="unitOfMeasure" label="单位" width="150"></el-table-column>
                    <el-table-column prop="quantityProduced" label="已完成数量" width="150"></el-table-column>
                    <el-table-column prop="clientCode" label="客户编码" width="150"></el-table-column>
                    <el-table-column prop="clientName" label="客户名称" width="150"></el-table-column>
                </el-table>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmitgd">确定</el-button>
                    <el-button @click="closegd">取消</el-button>
                </div>
            </template>

        </el-dialog>

        <!-- 新增产品弹窗 -->
        <el-dialog :destroy-on-close="true" :cptitle="cptitle" v-model="cpVisible" width="50%" @close="handleClosecp">
            <el-form ref="form" :model="cpformdata" label-width="100px">
                <el-row :gutter="24">
                    <el-col :span="12">
                        <el-form-item label="产品编号">
                            <el-input v-model="cpformdata.productCode" style="max-width: 600px" readonly>
                                <template #append>
                                    <el-button :icon="Search" @click="cpSelect" />
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="产品名称">
                            <el-input v-model="cpformdata.productName"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="入库数量">
                            <el-input-number v-model="cpformdata.quantityRecived" @change="handleChange" :min="0"
                                :max="2000" label="入库数量"></el-input-number>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="单位">
                            <el-input v-model="cpformdata.unitId"></el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="规格型号">
                            <el-input v-model="cpformdata.specificationAndModel"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="8">
                        <el-form-item label="选择仓库">
                            <el-cascader v-model="cpformdata.warehouseNames" ref="cascader" :options="options"
                                @change="handleChange" placeholder="请选择仓库" clearable></el-cascader>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="入库批次号">
                            <el-input v-model="cpformdata.batchCode" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="有效期">
                            <el-date-picker v-model="cpformdata.expireDate" type="date"
                                placeholder="选择日期"></el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="24">
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input type="textarea" v-model="cpformdata.remark" placeholder="请输入备注"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="cpOnSubmit">确定</el-button>
                    <el-button @click="cpclose">关闭</el-button>
                </div>
            </template>
        </el-dialog>



        <!-- 查询产品弹窗 -->
        <el-dialog :destroy-on-close="true" :title="titlecp" v-model="cpvisible" width="40%">
            <div style="display: flex; flex-direction: column; gap: 10px;">
                <el-table style="width: 100%" :data="cp" @row-click="handleRowClickcp3">
                    <el-table-column prop="productCode" label="产品编码" width="150"></el-table-column>
                    <el-table-column prop="productName" label="产品名称" width="150"></el-table-column>
                    <el-table-column prop="productSpc" label="规格型号" width="150"></el-table-column>
                    <el-table-column prop="unitOfMeasure" label="单位" width="150"></el-table-column>
                    <el-table-column prop="quantityProduced" label="入库数量" width="150"></el-table-column>
                </el-table>

            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="onSubmitcp">确定</el-button>
                    <el-button @click="closecp">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import {
    findProductRKD, findWorkOrder, insertProductRKD, updateProductRKD,
    deleteProductRKD, findline2, findWarehousesList, updateline2, deleteline2, insertStock, fedback, insertline2
} from '@/apis/xms';
import { Search, Refresh, Delete, Plus, EditPen, Edit } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';








const pageResult = ref({ total: 0 }); // 初始值包含 total 属性
const pageSizesline = [2, 5, 8, 10];//  分页大小  
const pageResultline = ref({ total: 0 }); // 分页数据
let salesorder = ref([]); // 表格数据
const visible = ref(false); // 新增修改入库单弹窗
const title = ref(""); // 新增修改弹窗标题
const gdtitle = ref(""); // 查询工单弹窗标题
const gdvisible = ref(false); // 查询工单弹窗
const gdsalesorder = ref([]); // 工单弹窗数据
const activeName = ref(false);// 弹窗tab页
const ids = ref([]); // 批量删除id数组
const deleteDisabled = ref(true);// 批量删除按钮禁用状态
const options = ref([]); // 仓库选择器数据
const idscp = ref([]); // 批量删除id数组
const titlecp = ref("");// 查询产品弹窗标题
const cpvisible = ref(false); // 查询产品弹窗
const cp = ref([]);// 产品弹窗数据

const isSingleRowSelected = ref(true) // 修改按钮禁用状态,默认禁用
let roleVal = ref([]); //选中行

const cpVisible = ref(false) // 新增产品弹窗
const cptitle = ref("") // 新增产品弹窗标题
const formdata = ref({
    recptCode: "",
    recptName: "",
    workorderCode: "",
    workorderName: "",
    recptDate: "",
    status: "PREPARE",
    remark: "",
    line: [],
});

const cpformdata = ref({
    productCode: "",
    productName: "",
    quantityRecived: "",
    wocumentAmount: 0,
    unitId: "",
    warehouseNames: [],
    batchCode: "",
    expireDate: "",
    remark: "",
    specificationAndModel: ""
});


// 仓库选择器数据
onMounted(async () => {
    options.value = await findWarehousesList();
});




const proWorkorder = ref({
    workorderCode: "",
    workorderName: "",
    productCode: "",
    productName: "",
});


// 分页大小
const pageSizes = [2, 5, 8, 10];
const params = ref({
    currentPage: 1,
    pageSize: 5,
    recptCode: "",
    recptName: "",
    recptDate: "",
});

const paramsline = ref({
    currentPage: 1,
    pageSize: 5,
    recptCode: '',
});

// 搜索条件
const handleSearch = async () => {
    pageResult.value = await findProductRKD(params.value)
    salesorder.value = pageResult.value.records
    console.log(salesorder.value)
}
//处理分页大小
const handleSizeChange = async (size) => {
    params.value.pageSize = size
    pageResult.value = await findProductRKD(params.value)
    salesorder.value = pageResult.value.records
}

//处理当前分页数据
const handleCurrentChange = async (currentPage) => {
    params.value.currentPage = currentPage
    pageResult.value = await findProductRKD(params.value)
    salesorder.value = pageResult.value.records


}


const handleSearchline = async () => {
    console.log(paramsline.value);
    pageResultline.value = await findline2(paramsline.value);
    //更新本地数据
    console.log("shuj", pageResultline.value)
    formdata.value.line = pageResultline.value.records[0].line;
};

const handleCurrentChangeline = async (currentPage) => {
    paramsline.currentPage = currentPage;
    await handleSearchline();
};

const handleSizeChangeline = async (size) => {
    paramsline.pageSize = size;
    await handleSearchline();
};

//查询数据
onMounted(async () => {
    pageResult.value = await findProductRKD(params.value)
    console.log(pageResult.value)
    salesorder.value = pageResult.value.records
})

//查询产品数据
onMounted(async () => {
    pageResultline.value = await findline2(paramsline.value)
    console.log(pageResultline.value)
})


//工单搜索功能
const onSearch = async () => {
    console.log(proWorkorder.value);
    pageResult.value = await findWorkOrder(proWorkorder.value)
    gdsalesorder.value = pageResult.value.records
}

//工单搜索条件重置
const onReset = async () => {
    Object.keys(proWorkorder.value).forEach(key => {
        proWorkorder.value[key] = null
    })
}


// 新增入库单弹窗
const insert = () => {
    visible.value = true;
    title.value = "新增入库单";
    activeName.value = false;
}

//修改入库单弹窗
const update = (row) => {
    visible.value = true;
    title.value = "修改入库单";
    formdata.value = { ...row };
    paramsline.value.recptCode = row.recptCode;
    console.log(formdata.value)
    activeName.value = true;
}


const updateid = () => {
    activeName.value = true;
    visible.value = true;
    title.value = "修改入库单";
}

//提交新增或修改入库单
const onSubmit = async () => {
    if (title.value === "新增入库单") {
        await insertProductRKD(formdata.value)
        ElMessage.success('新增入库单成功')
        visible.value = false;
        handleSearch()
    } else {
        await updateProductRKD(formdata.value)
        ElMessage.success('修改入库单成功')
        visible.value = false;
        handleSearch()
    }
}






const customerSelect = async () => {
    gdvisible.value = true;
    gdtitle.value = "工单选择";
    const result = await findWorkOrder();
    console.log(result);
    gdsalesorder.value = result;
    console.log(gdsalesorder.value)
}

// 工单行内点击事件处理
const handleRowClick = (row) => {
    // 确保 formdata 是一个对象
    if (typeof formdata.value !== 'object' || formdata.value === null) {
        console.error('formdata is not an object:', formdata.value);
        return;
    }
    // 更新 formdata 中的 supplierName
    formdata.value.workorderCode = row.workorderCode;
    formdata.value.workorderName = row.workorderName;
    formdata.value.productCode = row.productCode;
    formdata.value.productName = row.productName;
    console.log(formdata.value.workorderCode, formdata.value.workorderName);
};

// 确定按钮点击事件处理
const onSubmitgd = () => {
    // 检查 formdata 是否有有效的供应商名称
    if (formdata.value.workorderCode === '' || formdata.value.workorderName === '') {
        console.log(formdata.value);
        // 这里可以添加提交表单的逻辑
    } else {
        console.warn('');
    }

    // 关闭对话框
    gdvisible.value = false;
};

const handleSelectionChange = (val) => {
    ids.value = val
    deleteDisabled.value = !val.length
    ids.value = val.map(item => item.recptId) // 使用map方法过滤出选中行的logId数组

    roleVal.value = val.map(item => item); // 存储选中行的完整数据
    isSingleRowSelected.value = !(val.length === 1); // 如果只有一个选中行，则启用修改按钮
    if (!isSingleRowSelected.value) {
        formdata.value = { ...val[0] };//把选中的这条数据添加给修改数据（）
    }
}

//批量删除bom
const DeleteRKD = async (index, row) => {
    ElMessageBox.confirm(`是否确认删除访问编号为${ids.value.join(',')}的数据项？`, '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 调用删除API  
        await deleteProductRKD(ids.value);
        console.log(`删除的ID:`, ids.value);
        pageResult.value = await findProductRKD(params.value);
        console.log(pageResult.value)
        ids.value = [] // 重置选中行的id数组
        ElMessage({ type: 'success', message: '删除成功' });
        handleSearch();  // 重新查询数据  
    }).catch(() => {
        ElMessage({ type: 'info', message: '已取消删除' });
    });
};


//单个删除bom
const DeleteRKD1 = async (row) => {
    try {
        // 弹出确认框
        await ElMessageBox.confirm(
            `是否确认删除访问编号为${row.recptId}的数据项？`,
            '系统提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        // 调用删除API
        await deleteProductRKD([row.recptId]);
        console.log(`删除的ID:`, row.recptId);

        // 重新获取最新的数据
        pageResult.value = await findProductRKD(params.value);
        console.log(pageResult.value);

        // 如果需要，可以直接在这里处理页面更新逻辑

        handleSearch();

        // 提示删除成功
        ElMessage({ type: 'success', message: '删除成功' });
    } catch (error) {
        if (error instanceof Error) {
            // 用户点击了取消按钮
            ElMessage({ type: 'info', message: '已取消删除' });
        } else {
            // 处理其他错误
            ElMessage({ type: 'error', message: '删除失败，请稍后再试' });
            console.error('删除失败:', error);
        }
    }
};



// 新增产品弹窗
const cpinsert = () => {
    cpVisible.value = true;
    cptitle.value = "新增产品";
}

//修改产品弹窗
const cpupdate = (row) => {
    cpVisible.value = true;
    cptitle.value = "修改产品";
    cpformdata.value = { ...row };
    console.log("-----------------", cpformdata.value)
    const a = [];
    a.push(cpformdata.value.warehouseId + '')
    a.push(cpformdata.value.locationId + '')
    a.push(cpformdata.value.areaCode + '')
    cpformdata.value.warehouseNames = a
    console.log(cpformdata.value, a)
}




const cpSelect = async () => {
    cpvisible.value = true;
    titlecp.value = "产品选择";
    // 传递报工单号参数

    const result = await fedback({ workorderCode: formdata.value.workorderCode });
    console.log(formdata.value.workorderCode);
    console.log("233", result);
    cp.value = result;
}

const handleRowClickcp3 = (row) => {
    // 确保 cpformdata 是一个对象
    if (!isObject(cpformdata.value)) {
        console.error('cpformdata is not an object:', cpformdata.value);
        return;
    }

    // 更新 formdata
    cpformdata.value.productId = row.productId || ''; // 产品ID
    cpformdata.value.productCode = row.productCode || ''; // 产品编码
    cpformdata.value.productName = row.productName || ''; // 产品名称
    cpformdata.value.specificationAndModel = row.productSpc || '';   // 规格型号
    cpformdata.value.unitId = row.unitOfMeasure || ''; // 单位
    cpformdata.value.quantityRecived = row.quantityProduced || 0; // 数量




    // 日志输出
    console.log('Selected row data:', cpformdata.value);
};

// 辅助函数：检查是否为对象
function isObject(value) {
    return Object.prototype.toString.call(value) === '[object Object]';
}

const onSubmitcp = () => {

    cpvisible.value = false;
};

const cpOnSubmit = async () => {
    try {
        if (cptitle.value === "新增产品") {
            cpformdata.value.recptId = formdata.value.recptId;
            console.log(cpformdata.value.recptId);

            // 遍历 options.value 设置仓库、区域和库位信息
            options.value.forEach(item => {
                if (item.value === cpformdata.value.warehouseNames[0]) {
                    cpformdata.value.warehouseId = item.value + '';
                    cpformdata.value.warehouseName = item.label;

                    item.children.forEach(it => {
                        if (it.value === cpformdata.value.warehouseNames[1]) {
                            cpformdata.value.areaName = it.label + "";
                            cpformdata.value.areaId = it.value;

                            it.children.forEach(i => {
                                if (i.value === cpformdata.value.warehouseNames[2]) {
                                    cpformdata.value.locationCode = i.value + "";
                                    cpformdata.value.locationName = i.label;
                                }
                            });
                        }
                    });
                }
            });

            // 提交新增数据
            await insertline2(cpformdata.value);
        } else {
            // 提交修改数据
            await updateline2(cpformdata.value);
        }

        // 关闭弹窗
        cpVisible.value = false;

        // 提示操作成功
        ElMessage.success(`${cptitle.value}成功`);

        // 重新获取最新的数据

        await handleSearchline();




        // 重置表单数据
        cpformdata.value = {};
    } catch (error) {
        // 处理提交失败的情况
        ElMessage.error(`提交失败: ${error.message}`);
        console.error('提交失败:', error);
    }
};


const handleSelectionChangebom = (val) => {
    idscp.value = val
    deleteDisabled.value = !val.length
    idscp.value = val.map(item => item.lineId) // 使用map方法过滤出选中行的logId数组
}

// 批量删除 bom
const deletecp = async (index, row) => {
    try {
        // 弹出确认框
        await ElMessageBox.confirm(
            `是否确认删除访问编号为${idscp.value.join(',')}的数据项？`,
            '系统提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        // 调用删除 API
        await deleteline2(idscp.value);
        console.log(`删除的ID:`, idscp.value);

        // 重新获取最新的数据
        pageResultline.value = await findline2(paramsline.value);
        console.log(pageResultline.value);

        // 重置选中行的 id 数组
        idscp.value = [];

        // 提示删除成功
        ElMessage({ type: 'success', message: '删除成功' });

        // 重新获取最新的数据
        await handleSearchline();
    } catch (error) {
        if (error instanceof Error) {
            // 用户点击了取消按钮
            ElMessage({ type: 'info', message: '已取消删除' });
        } else {
            // 删除操作失败
            ElMessage({ type: 'error', message: '删除失败，请稍后再试' });
            console.error('删除失败:', error);
        }
    }
};

// 单个删除 bom
const Deletecp1 = async (row) => {
    try {
        // 弹出确认框
        await ElMessageBox.confirm(
            `是否确认删除访问编号为${row.lineId}的数据项？`,
            '系统提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        );

        // 调用删除 API
        await deleteline2([row.lineId]);
        console.log(`删除的ID:`, row.lineId);

        // 重新获取最新的数据
        pageResultline.value = await findline2(paramsline.value);
        console.log(pageResultline.value);

        // 如果需要，可以直接在这里处理页面更新逻辑
        // 例如：更新 formdata.value.line
        // 重新获取最新的数据

        await handleSearchline();

        // 提示删除成功
        ElMessage({ type: 'success', message: '删除成功' });
    } catch (error) {
        if (error instanceof Error) {
            // 用户点击了取消按钮
            ElMessage({ type: 'info', message: '已取消删除' });
        } else {
            // 删除操作失败
            ElMessage({ type: 'error', message: '删除失败，请稍后再试' });
            console.error('删除失败:', error);
        }
    }
};



//执行入库
const rk = async (row) => {
    row.status = 'CONFIRMED'
    await updateProductRKD(row)
    ElMessage.success('入库单已入库')
    handleSearch();
    console.log(row)
    row.line.forEach(item => {
        let a = reactive({})
        a.materialProductCode = item.productCode//产品编码
        a.materialProductName = item.productName//产品名称
        a.specificationAndModel = item.specificationAndModel//规格型号
        a.inventoryQuantity = item.quantityRecived//数量
        a.unitId = item.unitId//单位
        a.unitName = item.unitName //单位名称
        a.inboundBatchNumber = item.batchCode//批次号
        a.warehouseCode = item.warehouseCode//仓库编码
        a.warehouseAreaCode = item.areaCode//仓库区域编码
        a.warehouseLocationCode = item.locationCode//仓库库位编码
        a.workorderCode = row.workorderCode//生产订单号
        a.productionOrder = row.workorderCode//生产订单号
        a.indate = new Date()//入库时间
        a.expireDate = new Date()//有效期
        console.log("---------------------", a)

        // 添加接口调用
        insertStock(a)


    })
}



/**
 * 关闭弹窗,处理数据
 */
const handleClose = () => {
    resetData()
}


let closecp = () => {
    cpvisible.value = false;
}


/**
 * 重置数据
 */
function resetData() {
    formdata.value = {
        recptCode: "",
        recptName: "",
        workorderCode: "",
        workorderName: "",
        recptDate: "",
        status: "PREPARE",
        remark: "",
        line: [],
    }
    title.value = ''
}

let close = () => {
    visible.value = false;
    loadData();
};

let closegd = () => {
    gdvisible.value = false;
    loadData()
}


let cpclose = () => {
    cpVisible.value = false;
};




/**
 * 加载数据
 */
const loadData = async () => {
    await handleSearch();
};




/**
 * 重置搜索参数
 */
const paramsReset = () => {
    params.value = {
        currentPage: 1,
        pageSize: 5,
        recptCode: "",
        recptName: "",
        supplierName: "",
        recptDate: "",
        poCode: "",
    };
    paramsline1.value = {
        currentPage: 1,
        pageSize: 5,
        recptCode: '',
    };
    handleSearch();

}



</script>

<style scoped>
.demo-pagination-block {
    display: flex;
    /* 使其成为 flexbox 容器 */
    justify-content: flex-end;
    /* 将内容对齐到右侧 */
    margin-top: 20px;
}
</style>
